<?php


class Ext_Buddy_Validate
{
    protected $_controller;
    protected $_result = 1;
    protected $_messages = array();

    protected $_buddyUserId;
    protected $_loginUserId;
    
    const MESSAGE_NOT_LOGIN                              = 'notLogin';
    const MESSAGE_BUDDY_SELF_FORBIDDEN                   = 'buddySelfForbidden';
    const MESSAGE_IS_ALREADY_YOUR_BUDDY                  = 'isAlreadyYourBuddy';
    const MESSAGE_IS_NOT_YOUR_BUDDY_YET                  = 'isNotYourBuddyYet';
    protected $_messageTemplates = array(
        self::MESSAGE_NOT_LOGIN                          => "Please login.",
        self::MESSAGE_BUDDY_SELF_FORBIDDEN               => "You can't buddy your self.",
        self::MESSAGE_IS_ALREADY_YOUR_BUDDY              => "Is already your buddy.",
        self::MESSAGE_IS_NOT_YOUR_BUDDY_YET              => "Is not your buddy yet.",
    );
    
    public function __construct($loginUserId, $buddyUserId)
    {
        $this->_loginUserId = $loginUserId;
        $this->_buddyUserId = $buddyUserId;
        
		$this->_messager = new Ext_Messager($this->_messageTemplates);
    }
    
    public function validate($isBuddy)
    {
        if(!$this->_loginUserId){
            $this->_messager->addMessage(self::MESSAGE_NOT_LOGIN);
            $this->_result = 0;
            
            return "";
        }
        
        if($this->_loginUserId == $this->_buddyUserId){
            $this->_messager->addMessage(self::MESSAGE_BUDDY_SELF_FORBIDDEN);
            $this->_result = 0;
            
            return "";
        }
        
        $_appModelDbTableBuddy = App_Model_DbTable_Buddy::getInstance();
        $buddyRow = $_appModelDbTableBuddy->getRowByUserIdBuddyUserId($this->_loginUserId, $this->_buddyUserId);
        if($buddyRow){
            if($isBuddy != 1){
                $this->_messager->addMessage(self::MESSAGE_IS_ALREADY_YOUR_BUDDY);
                $this->_result = 0;
            }
        }
        else
        {
            if($isBuddy == 1){
                $this->_messager->addMessage(self::MESSAGE_IS_NOT_YOUR_BUDDY_YET);
                $this->_result = 0;
            }
        }
        
        return $this->_result;
    }
    
    public function isValid()
    {
        if($this->getResult())
        {
            return true;
        }
        return false;
    }
    
    public function getResult()
    {
        return $this->_result;
    }
    
    public function getMessages()
    {
        return $this->_messager->getMessages();
    }
}
